package com.ruoyi.project.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Anonymous;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.domain.SysPayOrder;
import com.ruoyi.project.system.domain.vo.FeeFrom;
import com.ruoyi.project.system.mapper.SysPayOrderMapper;
import com.ruoyi.project.system.service.ISysPayOrderService;
import com.ruoyi.project.system.service.ISysProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 进件查询支付Controller
 */
@Slf4j
@RestController
@RequestMapping("/pay")
public class SysQueryPayController extends BaseController {

    @Autowired
    private ISysPayOrderService iSysPayOrderService;

    @Autowired
    private ISysProductService sysProductService;

    @Autowired
    private SysPayOrderMapper sysPayOrderMapper;

    @Autowired
    private RedisCache redisCache;

    @GetMapping("/statistic/{productId}")
    public AjaxResult statistic(@PathVariable("productId") String productId) {
        return success(sysPayOrderMapper.statistic(SecurityUtils.getUserId(), productId));
    }

    /**
     * 新增余额查询付费
     */
    @PostMapping
    @Anonymous
    public AjaxResult balanceFee(@RequestBody FeeFrom feeFrom) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(feeFrom.getUserId(), "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!feeFrom.getCode().equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
        Float fee = sysProductService.getFee(feeFrom.getUserId().intValue(), feeFrom.getProductId());

        return null;
    }

    /**
     * 新增进件查询支付
     */
    @PostMapping
    @Anonymous
    public AjaxResult addPay(@RequestBody SysPayOrder sysQueryPay) {
        if (sysQueryPay.getOutId() == null ) {
            return error("缺少必须参数");
        }
        sysQueryPay.setOrderNo(IdUtils.fastSimpleUUID().substring(0, 8).toUpperCase());
        try {
            JSONObject payInfo = iSysPayOrderService.createPayInfo(sysQueryPay);
            payInfo.put("orderNo", sysQueryPay.getOrderNo());
            return success(payInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return error("发起支付异常！");
        }
    }

    /**
     * 修改支付订单(回调)
     */
    @Anonymous
    @GetMapping("/notify")
    public String notify(@RequestParam Map<String, String> map) {
        log.info("支付返回：" + map);
        if (map.isEmpty()) {
            return "err";
        }
        // 检证数据
        String str = map.get("state") + "1394150425178931200" + map.get("orderNo") + map.get("amount") + "086951d2cdb0b467c553b507d6f866db";       // 容易查
        String sign = Md5Utils.hash(str);
        if (!sign.equalsIgnoreCase(map.get("sign"))) {
            return "err";
        }
        // 您的代码块 start
        SysPayOrder sqp = iSysPayOrderService.selectSysPayOrderByOrderNo(map.get("orderNo"));
        if (sqp != null && "SUCCESS".equals(sqp.getPayState())) {
            return "success";
        }
        if ("1".equals(map.get("state"))) {         //支付成功
            // 短信通知
            AsyncManager.me().execute(AsyncFactory.report(sqp));
            //2.修改订单支付状态信息
            int update = iSysPayOrderService.updateSysPayOrder(new SysPayOrder(
                    map.get("orderNo"),
                    map.get("actualPayAmount"),
                    map.get("platformOrderNo"),
                    "SUCCESS",
                    DateUtils.parseDate(map.get("payTime"))
            ));
            return update == 1 ? "success" : "fail";
        } else {
            return "fail";
        }
    }

    /**
     * 退款
     */
    @GetMapping("/refund")
    public AjaxResult refund(SysPayOrder SysPayOrder) throws Exception {
        SysPayOrder.setRemark("REFUND:" + IdUtils.fastSimpleUUID().substring(0, 9).toUpperCase());
        return toAjax(iSysPayOrderService.refund(SysPayOrder));
    }

    /**
     * 获取我的合计统计
     */
    @GetMapping("/rankingList")
    public AjaxResult rankingList() {
        List<Map<String, Object>> maps = sysPayOrderMapper.rankingList();
        return success(maps).put("date", DateUtils.getTime());
    }

    /**
     * 获取我的合计统计
     */
    @GetMapping("/sum")
    public AjaxResult sumEarnings() {
        AjaxResult ajaxResult = new AjaxResult();
//        ajaxResult.put("sy_yj", sysPayOrderMapper.sumBrokerage(SecurityUtils.getUserId()));
//        ajaxResult.put("sy_tc", sysPayOrderMapper.sumRoyaltyByParent(SecurityUtils.getUserId()));
//        ajaxResult.put("tk_xjdl", sysPayOrderMapper.sumRoyaltyRefund(SecurityUtils.getUserId()));
//        ajaxResult.put("tk_yj", sysPayOrderMapper.sumBrokerageRefund(SecurityUtils.getUserId()));
        return ajaxResult;
    }


    @GetMapping("/count")
    public AjaxResult queryCount() {
        return AjaxResult.success(sysPayOrderMapper.selectSuccessPayCount(SecurityUtils.getUserId()));
    }

    /**
     * 查询进件查询支付列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysPayOrder sysQueryPay) {
        startPage();
        List<SysPayOrder> list = iSysPayOrderService.selectSysPayOrderList(sysQueryPay);
        return getDataTable(list);
    }

    /**
     * 导出进件查询支付列表
     */
    @PreAuthorize("@ss.hasPermi('system:pay:export')")
    @Log(title = "进件查询支付", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPayOrder sysQueryPay) {
        List<SysPayOrder> list = iSysPayOrderService.selectSysPayOrderList(sysQueryPay);
        ExcelUtil<SysPayOrder> util = new ExcelUtil<SysPayOrder>(SysPayOrder.class);
        util.exportExcel(response, list, "进件查询支付数据");
    }

    /**
     * 获取进件查询支付详细信息
     */
    @Anonymous
    @GetMapping(value = "/{orderNo}")
    public AjaxResult getInfo(@PathVariable("orderNo") String orderNo) {
        return success(iSysPayOrderService.selectSysPayOrderByOrderNo(orderNo));
    }

    /**
     * 修改进件查询支付
     */
    @PreAuthorize("@ss.hasPermi('system:pay:edit')")
    @Log(title = "进件查询支付", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysPayOrder sysQueryPay) {
        return toAjax(iSysPayOrderService.updateSysPayOrder(sysQueryPay));
    }

}
